#include "StdAfx.h"
#include "UserInfoManager.h"
#include "AppConfig.h"
#include "FreeMSDlg.h"

CUserInfoManager::CUserInfoManager(void)
{
	
	m_sockAddr.sin_addr.s_addr = htonl(INADDR_ANY);
	//m_sockAddr.sin_addr.s_addr = htonl(INADDR_BROADCAST);
	m_sockAddr.sin_family = AF_INET;
	m_sockAddr.sin_port = htons(BROADCAST_RECV_PORT);
//	m_asynP2PRecvSocket.SetSockWacher(&P2PSocketWatcher);
//	m_asynP2PSendSocket.SetSockWacher(&P2PSocketWatcher);
}

CUserInfoManager::~CUserInfoManager(void)
{
	UnInitalize();
}
BOOL CUserInfoManager::Initalize()
{
	BOOL bInit = FALSE;
	do 
	{
		if(!m_asynBcSocket.Initalize())
		{
			break;
		}
		if (!m_asynP2PSocket.Initalize())
		{
			break;
		}
		bInit = TRUE;
	} while (FALSE);

	return bInit;
}
BOOL CUserInfoManager::UnInitalize()
{
	m_asynBcSocket.UnInitalize();
	m_asynP2PSocket.UnInitalize();
	return TRUE;
}
BOOL CUserInfoManager::Login()
{
	return ChangeStateToAll(1);
}
BOOL CUserInfoManager::LogOff()
{
	return ChangeStateToAll(0);
}
BOOL CUserInfoManager::ChangeStateToAll(INT nStateCode)
{
	CUserInfo userInfo = g_pAppConfig->GetLocalUserInfo();
#if 0
	return ReplayToStateChanged(userInfo);
#endif
	userInfo.SetOnLine((nStateCode));
	CMsData sendData(MS_USER_INFO,(char *)&userInfo,sizeof(userInfo));
	INT nSendLen = m_asynBcSocket.Send(sendData.GetDataBuffer(),sendData.GetDataLen());
	return (nSendLen!=SOCKET_ERROR);
}
BOOL CUserInfoManager::ReplayToStateChanged(CUserInfo& userInfo)
{
	CUserInfo localUserInfo = g_pAppConfig->GetLocalUserInfo();
	CMsData sendData(MS_REPLY_USER_INFO,(char *)&localUserInfo,sizeof(localUserInfo));
	INT nSendLen = m_asynP2PSocket.SendTo(sendData.GetDataBuffer(),sendData.GetDataLen(),userInfo.GetIPAddress());
	//DWORD er = m_asynP2PSendSocket.GetLastError();
	return (nSendLen!=SOCKET_ERROR);
}